<template>
    <!-- 抽屉表单 -->
    <el-drawer
        v-if="Boolean(baTable.form.operate)"
        v-model="drawerVisible"
        :title="baTable.form.operate ? t(baTable.form.operate) : ''"
        direction="rtl"
        :destroy-on-close="true"
        size="80%"
        :close-on-click-modal="false"
        @close="onDrawerClose"
    >
        <el-scrollbar>
            <div class="drawer-form-content">
                <FormContent ref="formRef" :ba-table="baTable" />
            </div>
        </el-scrollbar>
        <template #footer>
            <div style="flex: auto;"></div>
            <el-button @click="baTable.toggleForm('', [])">{{ t('取消') }}</el-button>
            <el-button v-blur :loading="baTable.form.loading" type="primary" @click="handleSubmit">
                {{ baTable.form.loading ? t('提交中...') : t('保存') }}
            </el-button>
        </template>
    </el-drawer>

    <!-- 页面表单 -->
</template>

<script setup lang="ts">
import { inject, onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import FormContent from './formContent.vue'
import { useRouter } from 'vue-router'
import { FormInstance } from 'element-plus'
import baTableClass from '/@/utils/baTable'
import { ElMessage } from 'element-plus'

defineOptions({
    name: 'PopupForm'
})

// 定义FormContent组件实例的接口
interface FormContentInstance {
    formRef: FormInstance
    prepareSubmitData?: () => any
}

const { t } = useI18n()
const router = useRouter()
const baTable = inject('baTable') as baTableClass
const formRef = ref<FormContentInstance | null>(null)

// 修改计算属性
const drawerVisible = ref(true)

// 处理表单提交
// const handleSubmit = async () => {
//     if (!formRef.value) {
//         ElMessage.error('表单引用不存在')
//         return
//     }
    
//     try {
//         // 表单验证
//         await formRef.value.formRef.validate(async (valid: boolean) => {
//             if (!valid) {
//                 ElMessage.error('请检查表单是否填写正确')
//                 return
//             }
            
//             // 如果表单组件存在prepareSubmitData方法，则调用它处理数据
//             if (formRef.value && formRef.value.prepareSubmitData) {
//                 const formData = formRef.value.prepareSubmitData()
//                 // 提交表单
//                 baTable.onSubmit(formRef.value.formRef)
//             } else if (formRef.value) {
//                 // 直接提交表单
//                 baTable.onSubmit(formRef.value.formRef)
//             }
//         })
//     } catch (error) {
//         console.error('提交表单时发生错误:', error)
//         ElMessage.error('提交表单时发生错误')
//     }
// }
// popupForm.vue
const handleSubmit = async () => {
    if (!formRef.value) {
        ElMessage.error('表单引用不存在')
        return
    }
    try {
        await formRef.value.formRef.validate(async (valid: boolean) => {
            if (!valid) {
                ElMessage.error('请检查表单是否填写正确')
                return
            }
            if (formRef.value && formRef.value.prepareSubmitData) {
                const formData = formRef.value.prepareSubmitData()
                // 提交表单
                const res = await baTable.onSubmit(formRef.value.formRef)
                if (res && res.code === 1) {
                    // 关闭抽屉
                    drawerVisible.value = false
                    baTable.toggleForm('', [])
                    // 刷新表格
                    baTable.refreshTable && baTable.refreshTable()
                }
            } else if (formRef.value) {
                const res = await baTable.onSubmit(formRef.value.formRef)
                if (res && res.code === 1) {
                    drawerVisible.value = false
                    baTable.toggleForm('', [])
                    baTable.refreshTable && baTable.refreshTable()
                }
            }
        })
    } catch (error) {
        console.error('提交表单时发生错误:', error)
        ElMessage.error('提交表单时发生错误')
    }
}
// 添加抽屉关闭处理函数
const onDrawerClose = () => {
    baTable.toggleForm('', [])
}

onMounted(() => {
    // 检查URL是否包含add或edit参数，如果有则自动打开表单
    const pathSegments = router.currentRoute.value.path.split('/')
    const lastSegment = pathSegments[pathSegments.length - 1]
    const secondLastSegment = pathSegments[pathSegments.length - 2]

    if (secondLastSegment === 'add') {
        baTable.toggleForm('add', [])
    } else if (secondLastSegment === 'edit' && lastSegment && !isNaN(parseInt(lastSegment))) {
        baTable.toggleForm('edit', [lastSegment])
    }
})
</script>

<style lang="scss" scoped>
.drawer-form-content {
    padding: 20px;
}

.page-form-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--el-bg-color);
    z-index: 2000;
    display: flex;
    flex-direction: column;
}

.page-form-header {
    background-color: var(--el-bg-color);
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.page-form-title {
    font-size: 18px;
    font-weight: 500;
}

.page-form-scrollbar {
    height: calc(100vh - 60px);
}

.page-form-content {
    padding: 20px;
    max-width: 900px;
    margin: 0 auto;
}

@media (max-width: 768px) {
    .page-form-content {
        max-width: 100%;
    }
}
</style>

